//
//  NavigationViewManager+Pop.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/17.
//

import SwiftUI

extension NavigationViewManager {
    
    /// Pop 到指定类型的视图
    @discardableResult
    public func popToView<T: View>(tag: String, viewType: T.Type, animated: Bool) -> Bool {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            // 备选方案：全局查找
            return popToViewWithGlobalSearch(tag: tag, viewType: viewType, animated: animated)
        }
        
        let targetTypeName = String(describing: viewType)
        return performPopToView(navigationController: navigationController, targetTypeName: targetTypeName, animated: animated)
    }
    
    /// Pop 到指定标识符的视图
    @discardableResult
    public func popToView(tag: String, viewIdentifier: String, animated: Bool) -> Bool {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            // 备选方案：全局查找
            return popToViewWithGlobalSearch(tag: tag, viewIdentifier: viewIdentifier, animated: animated)
        }
        
        return performPopToView(navigationController: navigationController, viewIdentifier: viewIdentifier, animated: animated)
    }
    
    // MARK: - 私有方法
    
    private func popToViewWithGlobalSearch<T: View>(tag: String, viewType: T.Type, animated: Bool) -> Bool {
        guard let navigationController = findNavigationControllerGlobally() else {
            print("❌ NavigationViewKit: 全局搜索也未找到 NavigationController")
            return false
        }
        
        let targetTypeName = String(describing: viewType)
        print("⚠️ NavigationViewKit: 使用全局搜索的 NavigationController")
        return performPopToView(navigationController: navigationController, targetTypeName: targetTypeName, animated: animated)
    }
    
    private func popToViewWithGlobalSearch(tag: String, viewIdentifier: String, animated: Bool) -> Bool {
        guard let navigationController = findNavigationControllerGlobally() else {
            print("❌ NavigationViewKit: 全局搜索也未找到 NavigationController")
            return false
        }
        
        print("⚠️ NavigationViewKit: 使用全局搜索的 NavigationController")
        return performPopToView(navigationController: navigationController, viewIdentifier: viewIdentifier, animated: animated)
    }
    
    private func performPopToView(navigationController: UINavigationController, targetTypeName: String, animated: Bool) -> Bool {
        for viewController in navigationController.viewControllers {
            if isViewControllerOfType(viewController, matching: targetTypeName) {
                navigationController.popToViewController(viewController, animated: animated)
                print("✅ NavigationViewKit: 成功跳转到 \(targetTypeName)")
                return true
            }
        }
        
        print("❌ NavigationViewKit: 未找到类型为 \(targetTypeName) 的视图")
        return false
    }
    
    private func performPopToView(navigationController: UINavigationController, viewIdentifier: String, animated: Bool) -> Bool {
        for viewController in navigationController.viewControllers {
            if hasViewIdentifier(viewController, identifier: viewIdentifier) {
                navigationController.popToViewController(viewController, animated: animated)
                print("✅ NavigationViewKit: 成功跳转到标识符为 '\(viewIdentifier)' 的视图")
                return true
            }
        }
        
        print("❌ NavigationViewKit: 未找到标识符为 '\(viewIdentifier)' 的视图")
        return false
    }
    
    private func findNavigationControllerGlobally() -> UINavigationController? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            return nil
        }
        
        for window in windowScene.windows {
            if let navigationController = findNavigationController(in: window.rootViewController) {
                return navigationController
            }
        }
        
        return nil
    }
    
    private func findNavigationController(in viewController: UIViewController?) -> UINavigationController? {
        guard let viewController = viewController else { return nil }
        
        if let navigationController = viewController as? UINavigationController {
            return navigationController
        }
        
        for child in viewController.children {
            if let navigationController = findNavigationController(in: child) {
                return navigationController
            }
        }
        
        if let presented = viewController.presentedViewController {
            return findNavigationController(in: presented)
        }
        
        if let tabBarController = viewController as? UITabBarController,
           let selected = tabBarController.selectedViewController {
            return findNavigationController(in: selected)
        }
        
        return nil
    }
    
    private func isViewControllerOfType(_ viewController: UIViewController, matching typeName: String) -> Bool {
        // 检查 accessibility identifier
        if let accessibilityId = viewController.view.accessibilityIdentifier,
           accessibilityId == "type_\(typeName)" {
            return true
        }
        
        // 检查导航栏标题
        if let title = viewController.navigationItem.title, title == typeName {
            return true
        }
        
        // 检查 HostingController 的根视图类型
        if let hostingController = viewController as? UIHostingController<AnyView> {
            return checkViewType(hostingController.rootView, matching: typeName)
        }
        
        return false
    }
    
    private func hasViewIdentifier(_ viewController: UIViewController, identifier: String) -> Bool {
        // 检查 accessibility identifier
        if let accessibilityId = viewController.view.accessibilityIdentifier,
           accessibilityId == identifier {
            return true
        }
        
        // 检查导航栏标题
        if let title = viewController.navigationItem.title, title == identifier {
            return true
        }
        
        return false
    }
    
    private func checkViewType(_ view: AnyView, matching typeName: String) -> Bool {
        let mirror = Mirror(reflecting: view)
        return checkMirrorForType(mirror, typeName: typeName)
    }
    
    private func checkMirrorForType(_ mirror: Mirror, typeName: String) -> Bool {
        let subjectType = "\(mirror.subjectType)"
        
        // 检查当前类型
        if subjectType.contains(typeName) {
            return true
        }
        
        // 递归检查子视图
        for child in mirror.children {
            let childMirror = Mirror(reflecting: child.value)
            if checkMirrorForType(childMirror, typeName: typeName) {
                return true
            }
        }
        
        return false
    }
    
    /// 检查当前栈顶视图是否是特定类型
    public func isCurrentView<T: View>(tag: String, viewType: T.Type) -> Bool {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            return false
        }
        
        guard let topViewController = navigationController.topViewController else {
            return false
        }
        
        let targetTypeName = String(describing: viewType)
        return isViewControllerOfType(topViewController, matching: targetTypeName)
    }
    
    /// 检查当前栈顶视图是否具有特定标识符
    public func isCurrentView(tag: String, viewIdentifier: String) -> Bool {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            return false
        }
        
        guard let topViewController = navigationController.topViewController else {
            return false
        }
        
        return hasViewIdentifier(topViewController, identifier: viewIdentifier)
    }
    
    /// 获取当前栈顶视图的类型名称
    public func getCurrentViewTypeName(tag: String) -> String? {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            return nil
        }
        
        guard let topViewController = navigationController.topViewController else {
            return nil
        }
        
        // 尝试从 HostingController 获取类型信息
        if let hostingController = topViewController as? UIHostingController<AnyView> {
            return getViewTypeName(from: hostingController.rootView)
        }
        
        return String(describing: type(of: topViewController))
    }
    
    /// 获取当前栈顶视图的标识符
    public func getCurrentViewIdentifier(tag: String) -> String? {
        guard let navigationController = NavigationControllerStore.shared.getNavigationController(for: tag) else {
            print("❌ NavigationViewKit: 未找到标签为 '\(tag)' 的 NavigationController")
            return nil
        }
        
        guard let topViewController = navigationController.topViewController else {
            return nil
        }
        
        return topViewController.view.accessibilityIdentifier
    }
    
    // MARK: - 私有辅助方法
    
    private func getViewTypeName(from view: AnyView) -> String {
        let mirror = Mirror(reflecting: view)
        return extractTypeName(from: mirror)
    }
    
    private func extractTypeName(from mirror: Mirror) -> String {
        let subjectType = "\(mirror.subjectType)"
        
        // 清理类型名称，移除一些 SwiftUI 的内部标记
        let cleanedType = subjectType
            .replacingOccurrences(of: "NavigationViewHost<", with: "")
            .replacingOccurrences(of: ">", with: "")
            .replacingOccurrences(of: "ModifiedContent<", with: "")
            .replacingOccurrences(of: "_EnvironmentKeyWritingModifier<", with: "")
            .split(separator: "<").first ?? Substring(subjectType)
        
        return String(cleanedType)
    }
}
